package com.neusoft.yiyang.customer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.yiyang.common.entity.bed.Bed;
import com.neusoft.yiyang.common.entity.bed.BedUsage;
import com.neusoft.yiyang.common.entity.customer.vto.CheckInData;
import com.neusoft.yiyang.common.entity.customer.vto.CustomerWithTagBed;
import com.neusoft.yiyang.common.entity.diet.DietTag;
import com.neusoft.yiyang.common.enums.BedStatus;
import com.neusoft.yiyang.customer.client.*;
import com.neusoft.yiyang.common.entity.customer.Customer;
import com.neusoft.yiyang.customer.mapper.CustomerMapper;
import com.neusoft.yiyang.customer.service.CustomerService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private TaskClient taskClient;

    @Autowired
    private CareClient careClient;

    @Autowired
    private BedClient bedClient;

    @Autowired
    private DietClient dietClient;

    @Autowired
    private BedUsageClient bedUsageClient;

    @Override
    public void registerCustomer(Customer customer) {
        // 设置客户类型
        if (customer.getCareLevelId() != null) {
            customer.setCustomerType(1); // 护理老人
        } else {
            customer.setCustomerType(0); // 自理老人
        }

        // 保存客户信息
        customerMapper.insert(customer);

        // 通知任务服务客户信息变更
        if (customer.getCustomerType() == 1) {
            taskClient.handleCustomerUpdate(customer.getCustomerId());
        }
    }

    @Override
    public Customer getCustomerById(Integer customerId) {
        return customerMapper.selectById(customerId);
    }

    @Override
    public List<Customer> getAllCustomers() {
        // 创建查询条件，只查询is_deleted为0的记录
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", 0);
        queryWrapper.eq("customer_type",0);
        queryWrapper.isNull("expected_check_in_date");

        // 执行查询并返回结果
        return customerMapper.selectList(queryWrapper);

    }

    //获取所有老人
    @Override
    public List<Customer> selectAllCustomer(){
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", 0);
        queryWrapper.isNull("expected_check_in_date");
        return customerMapper.selectList(queryWrapper);
    }

    @Override
    public void addCustomerExpected(Customer customer) {
        customerMapper.insert(customer);
    }

    @Override
    public List<Customer> getAllCustomersExpected() {
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", 0);
        queryWrapper.isNotNull("expected_check_in_date");
        return customerMapper.selectList(queryWrapper);
    }

    @Override
    public void editCustomerExpected(Customer customer) {
        customerMapper.updateById(customer);
    }

    @Override
    public void deleteCustomerExpected(Integer customerId) {
        UpdateWrapper<Customer> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("customer_id", customerId);
        updateWrapper.set("is_deleted", 1);
        customerMapper.update(null, updateWrapper);
    }

    @Override
    public void confirmCheckIn(CheckInData checkInData) {
        Integer bedId = bedClient.getBedIdByLocation(checkInData.getBuilding(), checkInData.getFloor(), checkInData.getRoomNumber(), checkInData.getBedNumber());
        Bed bed = new Bed();
        bed.setBedId(bedId);
        bed.setStatus(BedStatus.occupied);
        bedClient.updateBed(bed);

        Customer customer = customerMapper.selectById(checkInData.getCustomerId());
        if (customer != null) {
            // 创建 UpdateWrapper 对象，根据 customerId 进行更新
            UpdateWrapper<Customer> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("customer_id", checkInData.getCustomerId())
                    .set("bed_id", bedId)
                    .set("check_in_date", checkInData.getCheckInDate())
                    .set("contract_end_date", checkInData.getContractEndDate())
                    .set("customer_type", checkInData.getCustomerType())
                    .set("expected_check_in_date", null);

            // 执行更新操作
            customerMapper.update(null, updateWrapper);
        }

        BedUsage bedUsage = new BedUsage();
        bedUsage.setBedId(bedId);
        bedUsage.setCustomerId(checkInData.getCustomerId());
        bedUsage.setStartDate(checkInData.getCheckInDate());
        bedUsage.setEndDate(checkInData.getContractEndDate());

        bedUsageClient.addBedUsage(bedUsage);

    }

    @Override
    public Map<String, Integer> getBedFreeStatus() {
        Map<String, Integer> ret = new HashMap<>();
        ret.put("total", bedClient.getAllBeds().size());
        ret.put("free", bedClient.getAllFreeBeds().size());
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", 0);
        queryWrapper.eq("is_moneyed", 0);
        queryWrapper.isNotNull("expected_check_in_date");
        ret.put("noMoneyed", customerMapper.selectList(queryWrapper).size());

        QueryWrapper<Customer> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("is_deleted", 0);
        queryWrapper1.eq("is_moneyed", 1);
        queryWrapper1.isNotNull("expected_check_in_date");
        ret.put("moneyed", customerMapper.selectList(queryWrapper1).size());

        return ret;
    }

    @Override
    public List<Customer> searchCustomers(String customerName, Integer customerType, Integer dietTagId, Integer caretakerId, String idCard) {
        // 创建查询条件
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();

        if (customerName != null) {
            queryWrapper.like("customer_name", customerName);  // 模糊查询客户姓名
        }

        if (customerType != null) {
            queryWrapper.eq("customer_type", customerType);  // 根据客户类型查询（0：自理老人，1：护理老人）
        }

        if (dietTagId != null) {
            queryWrapper.eq("diet_tag_id", dietTagId);  // 根据饮食标签查询
        }

        if (caretakerId != null) {
            queryWrapper.eq("caretaker_id", caretakerId);  // 根据健康管家查询
        }

        if (idCard != null) {
            queryWrapper.eq("id_card", idCard);
        }

        queryWrapper.eq("is_deleted", 0);
        queryWrapper.isNull("expected_check_in_date");

        return customerMapper.selectList(queryWrapper);  // 执行查询并返回结果
    }

    @Override
    public Page<Customer> pageQuery(Page<Customer> page, String customerName, Integer customerType, Integer careLevelId) {
        // 创建查询条件包装器
        LambdaQueryWrapper<Customer> wrapper = new LambdaQueryWrapper<>();

        // 姓名模糊查询
        if (customerName != null && !customerName.isEmpty()) {
            wrapper.like(Customer::getCustomerName, customerName);
        }

        // 客户类型查询
        if (customerType != null) {
            wrapper.eq(Customer::getCustomerType, customerType);
        } else {
            // 默认查询自理老人
            wrapper.eq(Customer::getCustomerType, 0);
        }

        // 护理等级查询
        if (careLevelId != null) {
            wrapper.eq(Customer::getCareLevelId, careLevelId);
        }

        // 只查询未删除的记录
        wrapper.eq(Customer::getIsDeleted, 0);

        wrapper.isNull(Customer::getExpectedCheckInDate);

        // 执行分页查询
        return customerMapper.selectPage(page, wrapper);
    }

    @Override
    public void updateCustomer(Customer customer) {
        customerMapper.updateById(customer);
    }

    @Override
    public void deleteCustomer(Integer customerId) {
        // 逻辑删除客户信息，并更新床位状态为“空闲”
        Customer customer = customerMapper.selectById(customerId);
        customer.setCustomerId(customerId);
        // 检查是否已分配床位
        if (customer.getBedId() != null) {
            throw new IllegalArgumentException("老人尚未退房，无法删除");
        }
        customer.setIsDeleted(1); // 逻辑删除标记
        customerMapper.updateById(customer);
    }

    @Override
    public void assignCaretaker(Integer customerId, Integer caretakerId) {
        Customer customer = customerMapper.selectById(customerId);
        if (customer == null) {
            throw new IllegalArgumentException("客户不存在，ID: " + customerId);
        }
        Integer currentCaretakerId = customer.getCaretakerId();
        // 如果护工没有变化，直接返回
        if (Objects.equals(currentCaretakerId, caretakerId)) {
            return;
        }
        // 更新客户护工信息
        customer.setCaretakerId(caretakerId);
        customerMapper.updateById(customer);
        // 通知任务服务客户信息变更（护工变更）
        taskClient.handleCustomerUpdate(customerId);
    }

    @Override
    public void setCareLevel(Integer customerId, Integer careLevelId) {
        // 1. 更新客户护理级别ID
        Customer customer = customerMapper.selectById(customerId);
        if (customer == null) {
            throw new IllegalArgumentException("客户不存在");
        }

        customer.setCareLevelId(careLevelId);
        // 2. 将客户类型改为护理老人
        customer.setCustomerType(1);
        customerMapper.updateById(customer);

        // 3. 调用care-service接口，为客户添加该护理级别下的所有护理项目
        careClient.addCareItemsByCareLevel(customerId, careLevelId);

        // 4. 通知任务服务客户信息变更
        taskClient.handleCustomerUpdate(customerId);
    }

    @Override
    public List<Customer> getCustomersWithCaretaker() {
        LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Customer::getCustomerType, 1) // 护理老人
                .isNotNull(Customer::getCaretakerId) // 已分配护工
                .eq(Customer::getIsDeleted, 0); // 未删除

        return customerMapper.selectList(queryWrapper);
    }


    @Override
    public void assignDietTag(Integer customerId, Integer dietTagId) {
        Customer customer = customerMapper.selectById(customerId);
        if (customer != null) {
            customer.setDietTagId(dietTagId);
            customerMapper.updateById(customer);
        }
    }

    @Override
    public void removeDietTag(Integer customerId) {
        Customer customer = customerMapper.selectById(customerId);
        if (customer != null) {
            customer.setDietTagId(null);
            customerMapper.updateById(customer);
        }
    }

    @Override
    public Integer getDietTagByCustomerId(Integer customerId) {
        Customer customer = customerMapper.selectById(customerId);
        return customer != null ? customer.getDietTagId() : null;
    }

    @Override
    public List<Customer> getCustomerByBed(List<Bed> beds) {
        return customerMapper.getCustomerByBed(beds);
    }

    @Override
    public List<Customer> getCustomerHasBed() {
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        wrapper.isNotNull("bed_id"); // 查询 bed_id 不为空的客户
        return customerMapper.selectList(wrapper);
    }

    @Override
    public void changeBed(Integer customerId, Integer bedId) {
        UpdateWrapper<Customer> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("customer_id", customerId)
                .set("bed_id", bedId);
        customerMapper.update(null, updateWrapper);
    }

    @Override
    public List<CustomerWithTagBed> getCustomerByUserId(Integer userId) {

        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("caretaker_id", userId);
        queryWrapper.eq("is_deleted", 0);
        List<Customer>  customers = customerMapper.selectList(queryWrapper);

        List<DietTag> dietTags = dietClient.getAllDietTags();

        Map<Integer, String> dietTagMap = dietTags.stream()
                .collect(Collectors.toMap(DietTag::getTagId, DietTag::getTagName));

        List<Integer> bedIds = new ArrayList<>();
        for (Customer customer : customers) {
            bedIds.add(customer.getBedId());
        }

        List<Bed> beds = bedClient.getByBedIds(bedIds);
        Map<Integer, Bed> bedMap = beds.stream()
                .collect(Collectors.toMap(Bed::getBedId, bed -> bed));

        List<CustomerWithTagBed> customerWithTagBeds = new ArrayList<>();
        for (Customer customer : customers) {
            CustomerWithTagBed customerWithTagBed = new CustomerWithTagBed(customer, dietTagMap.get(customer.getDietTagId()), bedMap.get(customer.getBedId()));
            customerWithTagBeds.add(customerWithTagBed);
        }

        return customerWithTagBeds;
    }

    @Override
    public Customer getCustomerByIdCard(String idCard) {
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id_card", idCard);
        return customerMapper.selectOne(queryWrapper);
    }


    @Override
    public List<Map<String, Object>> getCustomersByCaretakerId(Integer caretakerId){
        QueryWrapper<Customer> qw = new QueryWrapper<>();
        qw.eq("caretaker_id",caretakerId).eq("is_deleted", 0);
        List<Customer> matchedCustomers = customerMapper.selectList(qw);
        List<Map<String, Object>> result = new ArrayList<>();
        for (Customer customer : matchedCustomers) {
            Bed bed = bedClient.getBed(customer.getBedId());
            Map<String, Object> map = new HashMap<>();
            map.put("customer", customer);
            map.put("bed", bed);
            result.add(map);
        }
        return result;
    }
}
